package com.xzy.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 重构Servlet 该类作为Servlet的公共父类其他Servlet只需要继承该类就可以直接编写业务方法
 * 调用Servlet中某一业务方法时只需要将业务方法名通过req传入即可调用
 * 该类利用利用反射调用业务方法
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");//从req中获取需要调用的业务方法名
        try {
            //使用反射获取方法再调用
            Method method = this.getClass().getDeclaredMethod(type,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}
